package com.mingqijia.gassafety.shared.facade;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.mingqijia.gassafety.db.entity.auth.BaseEntry;
import com.mingqijia.gassafety.shared.constant.Constants;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.Value;

import java.util.List;
import java.util.Optional;

/**
 * 分页处理
 * @author damon S. on 16/8/30.
 */
@Getter
@NoArgsConstructor
public final class Pagination<T> {
    /***分页信息*/
    private PageInfo page;

    @Setter
    @JsonInclude(Include.NON_EMPTY)
    private List<T> records;

    private Pagination(Long pageIndex, Long pageSize,
                       Long totalSize, List<T> data) {
        this.records = data;
        this.page = new PageInfo(pageIndex, pageSize, totalSize);
    }
    
    public static <E extends BaseEntry, T> Pagination<T> init(IPage<E> results, List<T> data) {
        return new Pagination<>(results.getCurrent(), results.getSize(), results.getTotal(), data);
    }

    @Value
    public static class PageInfo {
        /***当前页码*/
        Long index;
        /***每页数量*/
        Long limit;
        /***数据总数*/
        Long total;
        /***总页数*/
        public Long getPages() {
            return Double.valueOf(String.valueOf(Math.ceil(total / (limit * 1.0d)))).longValue();
        }

        private PageInfo(Long index, Long limit, Long total) {
            this.total = Optional.ofNullable(total).orElse(Constants.LONG_ZERO);
            this.limit = Optional.ofNullable(limit).orElse(Constants.PAGE_SIZE);
            Long totalPages = getPages();
            this.index = index > totalPages ? totalPages : index;
        }
    }
}
